package org.blog.helper;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonMapper {
	private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
	
	private static ObjectMapper mapper = new ObjectMapper();
	
	static {
		// 不序列化空元素，包括null,""以及空Collection和Array
		mapper.setSerializationInclusion(Inclusion.NON_EMPTY);
		
	 	// 設定是否使用Enum的toString函數來讀寫Enum,
		// 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
		mapper.enable(SerializationConfig.Feature.WRITE_ENUMS_USING_TO_STRING);
		mapper.enable(DeserializationConfig.Feature.READ_ENUMS_USING_TO_STRING);
	}
	
	public static final String toJsonString(Object object) {
		try {
			return mapper.writeValueAsString(object);
		} catch (Exception e) {
			logger.warn("object to json exception", e);
			throw new RuntimeException(e);
		}
	}
	
	public static final <T> T toObject(String src, Class<T> cls) {
		try {
			return mapper.readValue(src, cls);
		} catch (Exception e) {
			logger.warn("json to object exception", e);
			throw new RuntimeException(e);
		}
	}
}
